﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Rhomble.ViewModels.Customers;
using Rhomble.Services.Customers;

namespace Rhomble.Controllers
{
	[Authorize]
    public class CustomerController : BaseController
    {
		private CustomerService _service;

		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			base.OnActionExecuting(filterContext);

			if (_service == null)
			{
				_service = new CustomerService(User.Identity.Name);
			}
		}

        public ActionResult Index()
        {
			var model = new IndexViewModel();

			model.Customers = _service.GetAll();

            return View(model);
        }

		public ActionResult Create()
		{
			var model = new CreateViewModel();

			return View(model);
		}

		[HttpPost]
		public ActionResult Create(CreateViewModel model)
		{
			if (!ModelState.IsValid)
			{
				return View(model);
			}

			_service.AddNew(model.Customer);

			return RedirectToAction("Index");
		}

		public ActionResult Edit(Guid id)
		{
			var model = new EditViewModel();
			model.Customer = _service.GetByID(id);

			return View(model);
		}

		[HttpPost]
		public ActionResult Edit(Guid id, EditViewModel model)
		{
			if (!ModelState.IsValid)
			{
				return Edit(id);
			}

			_service.Update(id, model.Customer);

			return RedirectToAction("Index");
		}
    }
}
